package cn.sdormitory.controller;

import cn.hutool.extra.qrcode.QrCodeUtil;
import cn.sdormitory.common.dto.ResultMsg;
import cn.sdormitory.common.utils.FileUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.net.URLEncoder;

@RestController
@RequestMapping("/app/common")
@Api("公共服务")
public class AppCommonController {
    @Value("${file.upload.path}")
    private String fileFolder;


    @ApiOperation(value = "上传文件")
    @PostMapping("/uploadFile")
    public ResultMsg uploadFile(@RequestParam("file")MultipartFile file){
        String filename = null;
        if(file.getSize()>1024 * 1024){
            return  ResultMsg.BY_FAIL("上传文件请控制在1M以内");
        }
        try{
            filename = FileUtil.uploadFile(file, fileFolder);
        }catch(Exception e){
            e.printStackTrace();
        }
        return  ResultMsg.BY_SUCCESS("上传成功",filename);
    }

    @ApiOperation(value = "下载文件")
    @GetMapping("/downloadFileImg")
    public void downloadFileImg(HttpServletRequest request, HttpServletResponse response, String filename){
        File file = new File(fileFolder+filename);

        // 如果文件不存在
        if (!file.exists()) {
            request.setAttribute("message", "您要下载的资源已被删除！！");
            System.out.println("您要下载的资源已被删除！！");
            return ;
        }
        FileInputStream in = null;
        OutputStream out = null;
        try{
            // 处理文件名
            String realname = filename.substring(filename.indexOf("/") + 1);
            // 设置响应头，控制浏览器下载该文件
            response.setHeader("content-disposition", "attachment;filename="
                    + URLEncoder.encode(realname, "UTF-8"));
            // 读取要下载的文件，保存到文件输入流
            in = new FileInputStream(fileFolder + filename);
            // 创建输出流
            out = response.getOutputStream();
            // 创建缓冲区
            byte buffer[] = new byte[1024];
            int len = 0;
            // 循环将输入流中的内容读取到缓冲区当中
            while ((len = in.read(buffer)) > 0) {
                out.write(buffer, 0, len);
            }
            in.close();
            out.close();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            try{
                if(in!=null)
                in.close();
                if(out!=null)
                out.close();
            }catch(Exception e){
                e.printStackTrace();
            }


        }

    }


}
